/**
 * Created with JetBrains PhpStorm.
 * User: shauan
 * Date: 20/12/13
 * Time: 23:13
 * To change this template use File | Settings | File Templates.
 */
var http = location.protocol;
var slaches = http.concat("//");
var host = slaches.concat(window.location.hostname);
var _pathApp = host.concat($('base').attr('href'));

$(document).ready(function(){
    $('#sa-select-month').attr('disabled',true);
    $('#sa-button-newAccount').attr('disabled',true);
    $('#sa-button-newAccount').addClass('disabled');
    /** Faz um pergunta antes de atualizar a pagina*/
    $('#sa-boxGeral-widgetConta').each(function(){
        window.onbeforeunload = function() {
            return "ATENÇÃO: Existe um processo em execução. \nTem certeza que deseja fazer isso?";
        }
    });

    var month_input = $('#sa-select-month').val();
    var data = new Date;
    var month = data.getMonth()+1;
    var year = data.getFullYear();
    var dataFrmContra ='';
    dataFrmContra +='data[Account][year]='+year;
    dataFrmContra +='&data[Account][month]='+month;
    $.ajax({
        type:'post',
        url:_pathApp+'indexs/verificAccount',
        data:dataFrmContra,
        beforeSend:function(){
            $('#sa-loading').html('');
            $('#sa-loading').html('<div class="modal-backdrop white  in"><img src="'+_pathApp+'/img/loading_48.GIF"></div>');
        },
        success:function(data){
            var dados = data.split('|');
            if(dados[0] > 0)
            {
                $('#sa-select-month').attr('disabled',false);
                $("#sa-select-month option:selected").addClass('text-error');
                $("#sa-boxGeral-widgetConta").removeClass('box-center');
                $("#sa-boxGeral-widgetItensContas").show();
                $("#sa-span-itensContas-year").html('');
                $("#sa-span-itensContas-year").html(year);
                $("#sa-span-itensContas-month").html('');
                $("#sa-span-itensContas-month").html(monthSpelled(month));
                $("#sa-input-Account-Accouunt_id").val(dados[1]);
                $("#sa-select-year option").each(function(){
                    var valor = $(this).val();
                    if(valor == year)
                    {
                        $("#sa-select-year option[value='"+valor+"']").attr('selected','selected');
                    }
                });
                $("#sa-select-month option").each(function(){
                    var valor_month = $(this).val();
                    if(parseInt(valor_month) == month)
                    {
                        $("#sa-select-month option[value='"+valor_month+"']").attr('selected','selected');
                    }
                });
                listItensDespesas();
                $('#sa-box-renda').slideDown('slow');
                $('#sa-button-newAccount').attr('disabled',true);
                $('#sa-button-newAccount').addClass('disabled');
                $('#sa-button-removeAccount').removeClass('disabled');
                $('#sa-button-removeAccount').attr('disabled',false);
                $('#sa-select-recipe_id option[value=""]').attr('selected',true);
                $('#sa-input-valorRenda').val('');

            }
            else
            {
                month_input != ''?$('#sa-box-renda').slideDown('slow'):'';
                $("#sa-boxGeral-widgetConta").addClass('box-center');
                $("#sa-boxGeral-widgetItensContas").hide();
                $("#sa-span-itensContas-year").html('');
                $("#sa-span-itensContas-month").html('');

            }
        },
        error:function(){},
        complete:function(){
            $('#sa-loading').html('');
        }
    });
});

$(function(){
    $('#sa-select-year').change(function(){
        var year = $('#sa-select-year option:selected').val();
        $('#sa-select-month').attr('disabled',true);
        $('#sa-box-renda').hide();
        $('#sa-button-removeAccount').addClass('disabled');
        $('#sa-button-removeAccount').attr('disabled',true);
        $('#sa-select-month option[value=""]').attr('selected',true);
        $('#sa-select-recipe_id option[value=""]').attr('selected',true);
        $('#sa-input-valorRenda').val('');
        $("#sa-boxGeral-widgetConta").addClass('box-center');
        $("#sa-boxGeral-widgetItensContas").hide();
        if(year != "")
        {
            $('#sa-select-month').attr('disabled',false);
            return false;
        }
        $('#sa-box-renda').hide();
        $('#sa-select-month option[value=""]').attr('selected',true);
        return true;
    });

    $('#sa-select-month').change(function(){
        var dataFrmContra = $('form[name="Account"]').serialize();
        var month = $('#sa-select-month option:selected').val();
        var year = $('#sa-select-year option:selected').val();
        $.ajax({
            type:'post',
            url:_pathApp+'indexs/verificAccount',
            data:dataFrmContra,
            beforeSend:function(){
                $('#sa-loading').html('');
                $('#sa-loading').html('<div class="modal-backdrop white  in"><img src="'+_pathApp+'/img/loading_48.GIF"></div>');
            },
            success:function(data){
                var dados = data.split('|');
                if(dados[0] > 0)
                {
                    $("#sa-select-month option:selected").addClass('text-error');
                    $("#sa-boxGeral-widgetConta").removeClass('box-center');
                    $("#sa-boxGeral-widgetItensContas").show();
                    $("#sa-span-itensContas-year").html('');
                    $("#sa-span-itensContas-year").html(year);
                    $("#sa-span-itensContas-month").html('');
                    $("#sa-span-itensContas-month").html(monthSpelled(month));
                    $("#sa-input-Account-Accouunt_id").val(dados[1]);
                    listItensDespesas();
                    $('#sa-box-renda').slideDown('slow');
                    $('#sa-button-newAccount').attr('disabled',true);
                    $('#sa-button-newAccount').addClass('disabled');
                    $('#sa-button-removeAccount').removeClass('disabled');
                    $('#sa-button-removeAccount').attr('disabled',false);
                    $('#sa-select-recipe_id option[value=""]').attr('selected',true);
                    $('#sa-input-valorRenda').val('');
                }
                else
                {
                    $('#sa-box-renda').slideDown('slow');
                    $("#sa-boxGeral-widgetConta").addClass('box-center');
                    $("#sa-boxGeral-widgetItensContas").hide();
                    $("#sa-span-itensContas-year").html('');
                    $("#sa-span-itensContas-month").html('');
                }
            },
            error:function(){},
            complete:function(){
                $('#sa-loading').html('');
            }
        });
    });

    $('#sa-input-valorRenda').focus(function(){
        var recipe_id = $('#sa-select-recipe_id option:selected').val();

        if(recipe_id =="")
        {
            alert('Selecione o Tipo de Renda!');
            $('#sa-select-recipe_id').focus();
            return false;
        }
        $('#sa-button-newAccount').attr('disabled',false);
        $('#sa-button-newAccount').removeClass('disabled');
        return true;
    });

    $('#sa-button-newAccount').click(function(){
        var dataFrmConta = $('form[name="Account"]').serializeArray();
        var valorRenda = $('#sa-input-valorRenda').val();
        var month = $('#sa-select-month option:selected').val();
        var year = $('#sa-select-year option:selected').val();
        if(valorRenda != "")
        {
            $("#sa-li-saldo #value-saldo").html(valorRenda);
            $("#sa-li-saldo #value-saldo").attr('data-value',valorRenda);
            $("#sa-li-renda #value-renda").html(valorRenda);
            $("#sa-li-renda #value-renda").attr('data-value',valorRenda);
        }
        else
        {
            $('#sa-button-newAccount').attr('disabled',true);
            $('#sa-button-newAccount').addClass('disabled');
            return false;
        }

        $.ajax({
            type:'post',
            url:_pathApp+'indexs/saveAccount',
            data:dataFrmConta,
            beforeSend:function(){
                $('#sa-loading').html('');
                $('#sa-loading').html('<div class="modal-backdrop white  in"><img src="'+_pathApp+'/img/loading_48.GIF"></div>');
            },
            success:function(data){
                if(!isNaN(data)){
                    $("#sa-boxGeral-widgetConta").removeClass('box-center');
                    $("#sa-boxGeral-widgetItensContas").show();
                    $('#sa-select-year').attr('disabled',true);
                    $('#sa-select-month').attr('disabled',true);
                    $('#sa-select-recipe_id').attr('disabled',true);
                    $('#sa-input-valorRenda').attr('disabled',true);
                    $('#sa-button-newAccount').attr('disabled',true);
                    $('#sa-button-newAccount').addClass('disabled');
                    $('#sa-button-removeAccount').removeClass('disabled');
                    $('#sa-button-removeAccount').attr('disabled',false);
                    $("#sa-span-itensContas-year").html('');
                    $("#sa-span-itensContas-year").html(year);
                    $("#sa-span-itensContas-month").html('');
                    $("#sa-span-itensContas-month").html(monthSpelled(month));
                    $("#sa-input-Account-Accouunt_id").val(data);
                }
                else
                {
                    alert('Error ao abrir uma nova conta.');
                }
            },
            error:function(data){
                alert('Error interno na aplicação. Contate o adminitrador do sistema!');
            },
            complete:function(){
                $('#sa-loading').html('');
            }
        });
    });

    $('#sa-button-removeAccount').click(function(){
        var Account_id = $('#sa-input-Account-Accouunt_id').val();
        if(Account_id != "")
        {
            $.ajax({
                type:'post',
                url:_pathApp+'indexs/removeAccount/'+Account_id,
                beforeSend:function(){
                    $('#sa-loading').html('');
                    $('#sa-loading').html('<div class="modal-backdrop white  in"><img src="'+_pathApp+'/img/loading_48.GIF"></div>');
                },
                success:function(data){
                    if(data !=0)
                    {
                        $("#sa-li-saldo #value-saldo").html("0,00");
                        $("#sa-li-saldo #value-saldo").attr('data-value',"0,00");
                        $("#sa-li-renda #value-renda").html("0,00");
                        $("#sa-li-renda #value-renda").attr('data-value',"0,00");
                        $("#sa-li-custo #value-custo").html("0,00");
                        $("#sa-li-custo #value-custo").attr('data-value',"0,00");
                        $("#sa-box-renda").hide();
                        $("#sa-boxGeral-widgetItensContas").slideUp('slow',function(){
                            $("#sa-boxGeral-widgetConta").addClass('box-center');
                        });
                        $('#sa-select-year').attr('disabled',false);
                        $('#sa-select-recipe_id').attr('disabled',false);
                        $('#sa-input-valorRenda').attr('disabled',false);
                        $('#sa-button-newAccount').attr('disabled',false);
                        $('#sa-button-newAccount').removeClass('disabled');
                        $('#sa-button-removeAccount').attr('disabled',true);
                        $('#sa-button-removeAccount').addClass('disabled');
                        $('#sa-select-year option[value=""]').attr('selected',true);
                        $('#sa-select-month option[value=""]').attr('selected',true);
                        $('#sa-select-recipe_id option[value=""]').attr('selected',true);
                    }
                },
                error:function(){},
                complete:function(){
                    $('#sa-loading').html('');
                }
            });
        }
    });

    $('#sa-link-openModalItensConta').click(function(){
        $('#sa-modal').modal('show');
        var Account_id = $('#sa-input-Account-Accouunt_id').val();
        $.ajax({
            url:_pathApp+"indexs/newItemAccount",
            beforeSend:function(){
                $('#sa-modal-body').html('');
                $('#sa-modal-body').html('<img src="'+_pathApp+'/img/loading_48.GIF">');
            },
            success:function(data){
                $("#sa-modal-header").show();
                $("#sa-modal-footer").html('');
                $("#sa-modal-footer").hide();
                $("#sa-modal-header #sa-modal-title").html('');
                $("#sa-modal-header #sa-modal-title").html('Novo Item Despesa');
                $("#sa-modal-header #sa-modal-button-close").show();
                $("#sa-modal-body").html('');
                $("#sa-modal-body").html(data);
                $('#sa-input-AccountsExpence-account_id').val(Account_id);
            },
            error:function(){},
            complete:function(){
                $('#sa-loading').html('');
            }
        });
    });

});

function monthSpelled(m){
    var intMonth = parseInt(m)
    var month = new Array("","Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro");
    return month[intMonth];
}

function deleteItemDespesa(a,c){
    var valor_total = $('#sa-valueTotalDespesa').attr('data-value');
    var saldoAtual = parseFloat($('#sa-li-saldo #value-saldo').attr('data-value'));
    // paga o valor digitado para um despesa expecifica.
    var valor_despesa = $('#sa-checkbox-ItemDespesa'+c).val();
    // substitue a virgula pelo ponto no valor_despesa.
    var valor_despesa = valor_despesa.replace(',','.');

    var total = parseFloat(valor_total)-parseFloat(valor_despesa);

    var total_saldoAtual = saldoAtual + parseFloat(valor_despesa);

    var accountexpense_id = a;
    if(accountexpense_id == ''){
        return false;
    }
    $.ajax({
        type:'post',
        url:_pathApp+"indexs/removeItensDespesa/"+accountexpense_id,
        beforeSend:function(){
            $('#sa-loading').html('');
            $('#sa-loading').html('<div class="modal-backdrop white  in"><img src="'+_pathApp+'/img/loading_48.GIF"></div>');
        },
        success:function(data){
            if(data ==1)
            {
                /* Alert in modal */
                $('#sa-modal').modal('show');
                $('#sa-modal-header').show();
                $('#sa-modal-header #sa-modal-title').html('');
                $('#sa-modal-header #sa-modal-title').html('Informação');
                $('#sa-modal-body').html('');
                $('#sa-modal-body').append('<h4 class="text-center text-success"></h4>');
                $('#sa-modal-body h4').html('O item da conta foi removido com sucesso!');
                $('#sa-modal-footer').show();
                $('#sa-modal-footer').html('<button type="button" class="btn btn-blue" id="sa-modal-footer-button-close" data-dismiss="modal" aria-hidden="true">Ok</button>');
                /* Alert in modal */
                $('#sa-valueTotalDespesa').html('');
                $('#sa-valueTotalDespesa').html(total);
                // limpar o atributo data-value.
                $('#sa-valueTotalDespesa').attr('data-value','');
                // adicionar um valor total para o atributo data-value.
                $('#sa-valueTotalDespesa').attr('data-value',total);

                $("#sa-li-saldo #value-saldo").html(total_saldoAtual);
                $("#sa-li-saldo #value-saldo").attr('data-value',total_saldoAtual);

                $("#sa-li-custo #value-custo").html(total);
                $("#sa-li-custo #value-custo").attr('data-value',total);
                return true;
            }
        },
        error:function(){},
        complete:function(){
            $('#sa-loading').html('');
        }
    });
}

function listItensDespesas(){
    var account_id = $("#sa-input-Account-Accouunt_id").val();
    if(account_id != null)
    {
        $.ajax({
            type:'post',
            url:_pathApp+'indexs/listItensDespesas/'+account_id,
            beforeSend:function(){
                $('#sa-list-ItensDespesa').html('');
                $('#sa-list-ItensDespesa').html('<div class="image-center"><img src="'+_pathApp+'/img/loading_48.GIF"></div>');
            },
            success:function(data){
                $('#sa-list-ItensDespesa').html('');
                $('#sa-list-ItensDespesa').html(data);
            },
            error:function(){},
            complete:function(){
                $('#sa-loading').html('');
            }
        });
    }
}

function pagarItemDespesa(c){
    var itemDespesa = $('#sa-checkbox-ItemDespesa'+c+':checked').val();
    var itemDespesa_valor = $('#sa-checkbox-ItemDespesa'+c).val();
    var itemDespesa_id = $('#sa-checkbox-ItemDespesa'+c).attr('data-value');
    var dados = 'data[AccountsExpense][id]='+itemDespesa_id;
    var itemDespesaPaga = parseFloat($('#sa-valueTotalDespesaPaga').attr('data-value'));
    var itemDespesaTotal = parseFloat($('#sa-valueTotalDespesa').attr('data-value'));
    var situation = 2;
    if(itemDespesa != null){
        situation = 1;
        valor_DespesaPaga = itemDespesaPaga + parseFloat(itemDespesa_valor);
        if(valor_DespesaPaga == itemDespesaTotal)
        {
            $('#sa-box-verValorDispesa').removeClass('red');
            $('#sa-box-verValorDispesa').addClass('green');
        }
    }
    else
    {
        valor_DespesaPaga = itemDespesaPaga - parseFloat(itemDespesa_valor);
        valor_DespesaPaga = parseFloat(valor_DespesaPaga).toFixed(2);

        if(valor_DespesaPaga != itemDespesaTotal)
        {
            $('#sa-box-verValorDispesa').removeClass('green');
            $('#sa-box-verValorDispesa').addClass('red');
        }
    }
    dados += '&data[AccountsExpense][situation_id]='+situation;
    $.ajax({
        type:'post',
        url:_pathApp+"indexs/pagaItemDespesa",
        data:dados,
        beforeSend:function(){
            $('#sa-list-ItensDespesa').append('<div class="image-center loading"></div>');
        },
        success:function(data){
            if(data == 1){
                $('#sa-valueTotalDespesaPaga').attr('data-value',valor_DespesaPaga);
                $('#sa-valueTotalDespesaPaga').html('');
                $('#sa-valueTotalDespesaPaga').html(valor_DespesaPaga);
            }
            else
            {
                $('#sa-modal').modal('show');
                $('#sa-modal-header').show();
                $('#sa-modal-header #sa-modal-title').html('');
                $('#sa-modal-header #sa-modal-title').html('Informação');
                $('#sa-modal-body').html('');
                $('#sa-modal-body').html(data);
                $('#sa-modal-footer').show();
                $('#sa-modal-footer').html('<button type="button" class="btn btn-blue" id="sa-modal-footer-button-close" data-dismiss="modal" aria-hidden="true">Ok</button>');
            }
        },
        error:function(){},
        complete:function(){
            $('.image-center').removeClass('loading');
        }
    });
}

